package com.ckk.springcloud.service;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author 陈昆昆
 * @version 1.0
 * @date 2020/6/16 15:18
 */
@Service
@DefaultProperties(defaultFallback = "paymentGlobalFallBack")
public class HystrixService
{
    public String paymentInfo_OK(Integer id){
        return "线程池："+Thread.currentThread().getName()+"ok"+id;
    }

    // 设置超过 3 秒采用服务降级
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeoutHandler",commandProperties = {
            @HystrixProperty(name="circuitBreaker.enabled",value = "true"),//是否开启断路器
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "10"),// 请求次数
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "10000"),// 时间窗口期
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "60")// 失败率
            // 加起来就是在10s内的10次请求中如果失败超过6次进入服务熔断
    })
    public String paymentInfo_Timeout(Integer id){
        int i = 10 /0;
//        try {
//            TimeUnit.SECONDS.sleep(1);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        return "线程池："+Thread.currentThread().getName()+"Timeout"+id;
    }
    // 异常后调用的方法
    public String paymentInfo_TimeoutHandler(Integer id){
        return "服务超时，调用服务降级成功";
    }

    // 2. 定义全局服务降级方法
    // 下面是全局 fallback
    public String paymentGlobalFallBack(){
        return "80：获取异常，调用方法为全局fallback";
    }
}
